package com.czk.codec;

import com.czk.utils.SerializationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/8/10 11:42
 */
public class ObjectDecoder extends ByteToMessageDecoder {
    private Class<?> clazz;

    public ObjectDecoder(Class<?> clazz) {
        this.clazz = clazz;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if (byteBuf.readableBytes() < 4) {
            return;
        }
        // 标记
        byteBuf.markReaderIndex();
        // 拿到长度
        int i = byteBuf.readInt();
        // 写入
        if ( i> byteBuf.readableBytes()) {
            byteBuf.resetReaderIndex();
            return;
        }

        byte[] bytes = new byte[i];
        byteBuf.readBytes(bytes);
        list.add(SerializationUtil.deserialize(bytes, clazz));
    }
}
